package tech.aistar.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import tech.aistar.entity.*;
import tech.aistar.service.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Controller
@RequestMapping("/Appointment")
public class AppointmentController {
    @Autowired
    private IAppointmentTimeService appointmentTimeService;
    @Autowired
    private ITenantService tenantService;
    @Autowired
    private IAgentService agentService;
    @Autowired
    private IHouseService houseService;
    @Autowired
    private IMessageService messageService;
    @Autowired
    private ISeeRoomTrendService seeRoomTrendService;
    @Autowired
    private IImageService iImageService;
    @Autowired
    private IHouseService iHouseService;

    @GetMapping("/TenantApp/{tenantId}")
    public String select(HttpServletRequest request,@PathVariable("tenantId") Integer tenantId) {
//        String tenantId = request.getParameter("tenantId");
        Tenant tenant = tenantService.selectById(Integer.valueOf(tenantId));
        request.setAttribute("tenant", tenant);
        List<AppointmentTime> appointmentTime = appointmentTimeService.selectByTenantId(Integer.valueOf(tenantId));
        request.setAttribute("appointmentTime", appointmentTime);
        List<Agent> agents = new ArrayList<>();
        List<House> houseList = new ArrayList<>();
        for (int i = 0; i < appointmentTime.size(); i++) {
            Agent agent = agentService.selectById(appointmentTime.get(i).getAgentId());
            agents.add(agent);
            House house = houseService.selectById(appointmentTime.get(i).getHouseId());
            houseList.add(house);
        }
        request.setAttribute("agent", agents);
        request.setAttribute("houseList",houseList);
        List<Message> messageStates = messageService.selectByState(tenant.getRegisterId());
        request.setAttribute("messageSize",messageStates.size());


        List<SeeRoomTrend> seeRoomTrends=seeRoomTrendService.selectThree();
        int i=0;
        for (SeeRoomTrend seeRoomTrend : seeRoomTrends) {
            i++;
            request.setAttribute("image"+i, iImageService.selectOneByHouseId(seeRoomTrend.getHouseId()));
            request.setAttribute("house"+i,iHouseService.selectByhouseId(seeRoomTrend.getHouseId()));
        }
        return "/personal_homepage/tenant/appointment";
    }

    @PostMapping("/delApp")
    public @ResponseBody
    Result deleteById(Integer id) {
        AppointmentTime appointmentTime = appointmentTimeService.selectById(id);
        int count = appointmentTimeService.deleteById(id);
        Tenant tenant = tenantService.selectById(appointmentTime.getTenantId());
        Integer registerId = agentService.selectById(appointmentTime.getAgentId()).getRegisterId();
        Message message = new Message(registerId,"租户"+tenant.getName()+"取消了对您的预约,电话"+tenant.getPhone(),new Date());
        messageService.insertAll(message);

        if (count == 1) {
            Result result = new Result("200", "取消成功");
            return result;
        } else {
            Result result = new Result("500", "取消失败");
            return result;
        }
    }


    @PostMapping("/changeTime")
    public @ResponseBody
    Result updateById(Integer id, String appointmentDates, String timeQuantum, String agentId, Integer tenantId) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date appointmentDate = sdf.parse(appointmentDates);
        AppointmentTime appointmentTime = appointmentTimeService.selectById(id);
        Date date = appointmentTime.getAppointmentDate();
        String app = sdf.format(date);
        String time = appointmentTime.getTimeQuantum();
        String a = app.concat("/");
        String apptime = a.concat(time);
        AppointmentTime appointmentTimes = appointmentTimeService.selectByAppointmentDate(appointmentDate,timeQuantum,Integer.valueOf(agentId));
        AppointmentTime appointmentTimess = appointmentTimeService.selectByAppointmentDates(appointmentDate,timeQuantum,tenantId);
        if (appointmentTimes !=null) {
            return new Result("500","更改失败",apptime);
        } else if (appointmentTimess !=null){
            return new Result("800","更改失败",apptime);
        } else {
            int count = appointmentTimeService.updateById(appointmentDate, timeQuantum, id);
            if (count == 1) {
                Tenant tenant = tenantService.selectById(tenantId);
                Integer registerId = agentService.selectById(Integer.valueOf(agentId)).getRegisterId();
                Message message = new Message(registerId,"租户"+tenant.getName()+"修改了对您的预约时间,请到租户预约一栏进行确认",new Date());
                messageService.insertAll(message);
                return new Result("200", "修改成功");
            } else {
                return new Result("500", "修改失败", apptime);
            }
        }

    }
    @PostMapping("/nochangeTime")
    public @ResponseBody
    Result selectById(Integer id) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        AppointmentTime appointmentTime = appointmentTimeService.selectById(id);
        Date date = appointmentTime.getAppointmentDate();
        String app = sdf.format(date);
        String time = appointmentTime.getTimeQuantum();
        String a = app.concat("/");
        String apptime = a.concat(time);
        return new Result("200", "取消成功",apptime);
    }




    @GetMapping("/AgentApp/{agentId}")
    public String selectByAgentId(HttpServletRequest request,@PathVariable("agentId") Integer agentId) {
//        String agentId = request.getParameter("agentId");
        Agent agent = agentService.selectById(Integer.valueOf(agentId));
        request.setAttribute("agent", agent);
        List<AppointmentTime> appointmentTime = appointmentTimeService.selectByAgentId(Integer.valueOf(agentId));
        request.setAttribute("appointmentTime", appointmentTime);
        List<Tenant> tenants = new ArrayList<>();
        List<House> houseList = new ArrayList<>();
        for (int i = 0; i < appointmentTime.size(); i++) {
            Tenant tenant = tenantService.selectById(appointmentTime.get(i).getTenantId());
            tenants.add(tenant);
            House house = houseService.selectById(appointmentTime.get(i).getHouseId());
            houseList.add(house);
        }
        request.setAttribute("tenant", tenants);
        request.setAttribute("houseList",houseList);
        List<Message> messageStates = messageService.selectByState(agent.getRegisterId());
        request.setAttribute("messageSize",messageStates.size());
        return "/personal_homepage/broker/myappointment";
    }



    @PostMapping("/changeTrue")
    public @ResponseBody
    Result StatetrueById(Integer id,String appointmentDates,String timeQuantum,Integer agentId,Integer tenantId) throws ParseException {
        int count = appointmentTimeService.updateStateById(id);
        if (count==1){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date appointmentDate = sdf.parse(appointmentDates);
            AppointmentTime appointmentTime = new AppointmentTime(id,appointmentDate,timeQuantum,agentId);
            List<AppointmentTime> appmessage = appointmentTimeService.selectBy(appointmentTime);
            int counts = appointmentTimeService.updateStateBy(appointmentTime);
            Integer registerId = tenantService.selectById(tenantId).getRegisterId();
            Message message = new Message(registerId,"您已成功预约经纪人，请到租户预约一栏进行查看",new Date());
            messageService.insertAll(message);

            for (int i = 0; i <appmessage.size() ; i++) {
                Integer registerId2 = tenantService.selectById(appmessage.get(i).getTenantId()).getRegisterId();
                Message message2 = new Message(registerId2,"您预约经纪人失败,请到租户预约一栏进行查看以及修改预约时间",new Date());
                messageService.insertAll(message2);
            }
            return new Result("200","确认成功");
        }else{
            return new Result("500","确认失败");
        }

    }

    @PostMapping("/changeFalse")
    public @ResponseBody
    Result StatefalseById(Integer id,Integer tenantId) {
        int count = appointmentTimeService.updateStatefById(id);
        if (count==1){
            Integer registerId = tenantService.selectById(tenantId).getRegisterId();
            Message message = new Message(registerId,"您预约经纪人失败,请到租户预约一栏进行查看以及修改预约时间",new Date());
            messageService.insertAll(message);
            return new Result("200","取消成功");
        }else{
            return new Result("500","取消失败");
        }

    }




}
